<template>
	<!-- 添加自定義導航欄 -->
	<uni-nav-bar
		title="添加站點"
		:fixed="true"
		:status-bar="true"
		right-text="缺失上報"
		background-color="#00B26A"
		color="#FFFFFF"
		@clickRight="onClickRight"
	>
		<template v-slot:default>
			<view class="nav-title">添加站點</view>
		</template>
	</uni-nav-bar>
	
	<view class="search-container">
		<uni-search-bar
			v-model="searchValue"
			:radius="100"
			placeholder="請輸入搜索內容"
			clearButton="auto"
			cancelButton="none"
			@confirm="search"
			@input="onInput"
		/>
	</view>
	
	<!-- 添加列表容器 -->
	<view class="list-container">
		<view v-if="loading" class="loading">加載中...</view>
		<view v-else-if="error" class="error">{{ error }}</view>
		<view v-else class="list">
			<view v-for="item in items" :key="item.id" class="list-item" @click="navigateToDetail(item.id)">
				<image src="/static/logo.png" mode="aspectFill" class="item-image"></image>
				<text class="item-title">{{ item.name }}</text>
			</view>
		</view>
	</view>

	<!-- 在原有模板最後添加彈框組件 -->
	<uni-popup ref="popup" type="center">
		<view class="popup-content">
			<view class="popup-title">{{notices.title}}</view>
			<view class="popup-body">
				<view class="notice-item">
					<text class="notice-text">{{ notices.content }}</text>
					<text class="notice-time">{{ notices.createtime }}</text>
				</view>
			</view>
			<button class="popup-button" @click="closePopup">确定</button>
		</view>
	</uni-popup>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
// import { onLoad } from '@dcloudio/uni-app'
import {handleNotice, NoticeData, handleList, ListData} from '@/api/index'

// 搜索關鍵詞
const searchValue = ref<string>('')

// 列表狀態
const items = ref<ListData[]>([])
const loading = ref<boolean>(false)
const error = ref<string>('')



// 通告數據
const notices = ref<NoticeData>()

// 彈框引用
const popup = ref<any>(null)

// 打開彈框方法
const showPopup = () => {
	popup.value.open()
}

// 關閉彈框方法
const closePopup = () => {
	popup.value.close()
}

// 添加跳轉方法
const navigateToDetail = (id: number): void => {
    uni.navigateTo({
        url: `/pageDetail/index?title=大麦鲸选`,
        success: () => {
            console.log('跳轉成功')
        },
        fail: (err) => {
            console.error('跳轉失敗', err)
            uni.showToast({
                title: '頁面跳轉失敗',
                icon: 'none'
            })
        }
    })
}
// 獲取列表數據
const fetchList = async (): Promise<void> => {
	loading.value = true
	error.value = ''
	
	try {
		// 模擬 API 調用
		const response = await new Promise<ListData[]>((resolve) => {
			handleList(searchValue.value).then((res) => {
				console.log(res)
				resolve(res.data)
			})
			// setTimeout(() => {
			// 	resolve([
			// 		{ 
			// 			id: 1, 
			// 			title: '項目 1',
			// 			imageUrl: '/static/logo.png'
			// 		},
			// 		{ 
			// 			id: 2, 
			// 			title: '項目 2',
			// 			imageUrl: '/static/logo.png'
			// 		},
			// 		{ 
			// 			id: 3, 
			// 			title: '項目 3',
			// 			imageUrl: '/static/logo.png'
			// 		},
			// 		{ 
			// 			id: 4, 
			// 			title: '項目 4',
			// 			imageUrl: '/static/logo.png'
			// 		},
			// 		{ 
			// 			id: 5, 
			// 			title: '項目 5',
			// 			imageUrl: '/static/logo.png'
			// 		}
			// 	])
			// }, 1000)
		})
		
		items.value = response
	} catch (e) {
		error.value = '獲取數據失敗'
		console.error(e)
	} finally {
		loading.value = false
	}
}

// 添加防抖函數
const debounce = <T extends (...args: any[]) => any>(
	fn: T,
	delay: number
): ((...args: Parameters<T>) => void) => {
	let timeoutId: ReturnType<typeof setTimeout>
	
	return (...args: Parameters<T>) => {
		clearTimeout(timeoutId)
		timeoutId = setTimeout(() => {
			fn(...args)
		}, delay)
	}
}

// 修改搜索方法
const search = async (e: string): Promise<void> => {
	console.log('搜索內容：', searchValue.value)
	await fetchList() // 執行搜索時重新獲取列表
}

// 使用防抖處理輸入事件
const debouncedSearch = debounce(search, 500)

// 輸入事件處理
const onInput = (value: string): void => {
	console.log('當前輸入：', value)
	debouncedSearch(value)
}

// 生命週期鉤子
onMounted(() => {
	handleNotice().then((res) => {
		console.log(res)
		if (res) {
			notices.value = res.data;
			showPopup()
		}
		
	})
	// fetchList() // 頁面加載時獲取列表
	
})



// 方法可以直接定義為函數
const someMethod = () => {
	// 方法邏輯
}

// 添加右側按鈕點擊事件處理
const onClickRight = (): void => {
	uni.navigateTo({
		url: '/pageHome/lose',
		fail: (err) => {
			uni.showToast({
				title: '頁面跳轉失敗',
				icon: 'none'
			})
		}
	})
}
</script>

<style lang="scss">
.search-container {
	// margin-top: 44px; // 如果有狀態欄，可能需要調整這個值
	padding: 10px 15px;
}

.list-container {
	padding: 15px;
	
	.loading, .error {
		text-align: center;
		padding: 20px;
	}
	
	.list {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		gap: 15px;
	}
	
	.list-item {
		width: calc(25% - 12px);
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8px;
		
		.item-image {
			width: 100%;
			height: 60px;
			border-radius: 8px;
		}

		.item-title {
			font-size: 14px;
			text-align: center;
		}
	}
}

.nav-title {
	font-size: 18px;
	font-weight: bold;
	text-align: center;
	width: 100%;
	height: 44px;
	line-height: 44px;
	display: flex;
	justify-content: center;
	align-items: center;
}

// 修改彈框樣式
.popup-content {
	background-color: #fff;
	border-radius: 15px;
	padding: 20px;
	width: 80vw;
	position: relative;  // 添加相對定位
	z-index: 9999;      // 添加較高的z-index值
	
	.popup-title {
		font-size: 18px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 15px;
		color: #333;
	}
	
	.popup-body {
		max-height: 60vh;
		overflow-y: auto;
		
		.notice-item {
			padding: 10px 0;
			border-bottom: 1px solid #eee;
			
			&:last-child {
				border-bottom: none;
			}
			
			.notice-text {
				font-size: 14px;
				color: #333;
				display: block;
				margin-bottom: 5px;
			}
			
			.notice-time {
				font-size: 12px;
				color: #999;
			}
		}
	}
	
	.popup-button {
		margin-top: 15px;
		background-color: #00B26A;
		color: #fff;
		border-radius: 25px;
		font-size: 16px;
		
		&:active {
			opacity: 0.8;
		}
	}
}

// 可以添加一個全局樣式來確保彈窗始終在最上層
:deep(.uni-popup) {
	z-index: 9998;
}
</style>
